package com.authine.cloudpivot.ext.applicationservice.organization;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.Exceptions;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.system.OrganizationAttributeDto;
import com.authine.cloudpivot.ext.dto.system.SelectText;
import com.authine.cloudpivot.ext.enums.system.OrganizationAttributeEnum;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.authine.mvp.app.launcher.dto.errorcode.ErrorCodeEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName OrganizationAttributeApi
 * @Description: 组织属性api
 * @Author fj
 * @Date 2021/7/2
 * @Version V1.0
 **/
@Path("OrganizationAttributeApi")
@Slf4j
public class OrganizationAttributeApi {

    /**
     * 判断对应组织属性是否开启
     *
     * @param orgAttribute 组织属性请求参数
     * @return boolean          true：开启 false：未开启
     */
    @Path("isEnabledAttribute")
    @POST
    @Operation(summary = "判断对应组织属性是否开启", tags = CUSTOM_SERVICE)
    public boolean isEnabledAttribute(@Parameter OrganizationAttributeDto orgAttribute) {
        List<Map<String, Object>> orgAttributeResultList = Objects.requireNonNull(JdbcTemplateUtils.builder(ModelConst.T_ORGANIZATION_ATTRIBUTE).selectField("*"))
                .eq("organization_id", orgAttribute.getOrganization_id())
                .eq("attribute", orgAttribute.getAttribute())
                .queryForList();
        log.info("------------------------通过组织id和组织属性获取组织属性列表：{}------------------------", JSONObject.toJSONString(orgAttributeResultList));
        boolean result;
        if (CollectionUtils.isEmpty(orgAttributeResultList)) {
            result = false;
        } else {
            result = "1".equals(String.valueOf(orgAttributeResultList.get(0).get("enabled")));
        }
        return result;
    }

    /**
     * 获取组织属性信息
     *
     * @param orgAttribute 组织属性请求参数
     * @return 组织属性列表
     */
    @Path("getOrganizationAttribute")
    @POST
    @Operation(summary = "获取组织属性信息", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> getOrganizationAttribute(@Parameter OrganizationAttributeDto orgAttribute) {
        List<Map<String, Object>> orgAttributeResultList = Objects.requireNonNull(JdbcTemplateUtils.builder(ModelConst.T_ORGANIZATION_ATTRIBUTE).selectField("*"))
                .eq("organization_id", orgAttribute.getOrganization_id())
                .eq("enabled", 1)
                .queryForList();
        BOList boList = new BOList();
        log.info("------------------------通过组织id获取组织属性列表：{}------------------------", JSONObject.toJSONString(orgAttributeResultList));

        // 设置组织属性
        List<Map<String, Object>> orgAttributeList = Lists.newArrayList();
        Map<String, Object> orgAttributeMap;
        for (OrganizationAttributeEnum attributeEnum : OrganizationAttributeEnum.values()) {
            orgAttributeMap = Maps.newHashMap();
            orgAttributeMap.put("attribute_id", attributeEnum.ordinal());
            orgAttributeMap.put("attribute", attributeEnum.name());
            orgAttributeMap.put("attribute_description", attributeEnum.getDes());
            orgAttributeMap.put("enabled", 0);// 默认不开启
            orgAttributeList.add(orgAttributeMap);
        }

        // 存在组织属性，设置是否开启
        if (!CollectionUtils.isEmpty(orgAttributeResultList)) {
            orgAttributeResultList.forEach(attributeMap -> {
                for (Map<String, Object> map : orgAttributeList) {
                    if (String.valueOf(attributeMap.get("attribute")).equals(map.get("attribute"))) {
                        map.put("enabled", attributeMap.get("enabled"));
                        break;
                    }
                }
            });
        }

        // 设置返回结果
        boList.setSchemaCode(ModelConst.T_ORGANIZATION_ATTRIBUTE);
        boList.setData(orgAttributeList);
        boList.setTotal(orgAttributeList.size());
        log.info("--------End of method,methodName：{}--------", Thread.currentThread().getStackTrace()[1].getMethodName());
        return SingleResponse.of(boList);
    }

    /**
     * 获取所有组织属性
     *
     * @return 组织属性列表
     */
    @Path("getALLAttribute")
    @POST
    @Operation(summary = "获取所有组织属性", tags = CUSTOM_SERVICE)
    public SingleResponse<List<SelectText>> getALLAttribute() {
        List<SelectText> selectTextList = Lists.newArrayList();
        SelectText selectText;
        JSONObject jsonValue;

        for (OrganizationAttributeEnum attributeEnum : OrganizationAttributeEnum.values()) {
            selectText = new SelectText();
            jsonValue = new JSONObject();
            // 设置value值为json对象，前端拿到后自己解析
            jsonValue.put("attribute_id", attributeEnum.ordinal());
            jsonValue.put("attribute", attributeEnum.name());
            jsonValue.put("attribute_description", attributeEnum.getDes());

            selectText.setLabel(attributeEnum.getDes().concat(attributeEnum.name()));
            selectText.setValue(jsonValue.toJSONString());
            selectTextList.add(selectText);
        }
        return SingleResponse.of(selectTextList);
    }

    /**
     * 组织属性启禁用(批量操作)
     *
     * @param orgAttributeList 组织属性请求参数
     * @return 响应结果
     */
    @Path("enabledOrgAttribute")
    @POST
    @Operation(summary = "组织属性启禁用(批量操作)", tags = CUSTOM_SERVICE)
    public SingleResponse<Boolean> enabledOrgAttribute(@Parameter List<OrganizationAttributeDto> orgAttributeList) {
        Assert.notEmpty(orgAttributeList, "组织属性不能为空，请选择要添加的组织属性");

        List<Map<String, Object>> orgAttributeResultList;
        Map<String, Object> orgAttributeMap;

        for (OrganizationAttributeDto orgAttribute : orgAttributeList) {
            orgAttributeResultList = Objects.requireNonNull(JdbcTemplateUtils.builder(ModelConst.T_ORGANIZATION_ATTRIBUTE).selectField("*"))
                    .eq("organization_id", orgAttribute.getOrganization_id())
                    .eq("attribute", orgAttribute.getAttribute())
                    .queryForList();

            if (CollectionUtils.isEmpty(orgAttributeResultList)) {
                // 不存在时新增
                orgAttributeMap = Maps.newHashMap();
                orgAttributeMap.put("attribute", orgAttribute.getAttribute());
                orgAttributeMap.put("organization_id", orgAttribute.getOrganization_id());
                orgAttributeMap.put("enabled", orgAttribute.getEnabled());
                orgAttributeMap.put("attribute_id", orgAttribute.getAttribute_id());
                orgAttributeMap.put("attribute_description", orgAttribute.getAttribute_description());
                log.info("------------------------创建组织属性数据，：{}------------------------", JSONObject.toJSONString(orgAttributeMap));
                SingleResponse<BO> orgAttributeCreateBO = BoServiceUtils.createBo(ModelConst.T_ORGANIZATION_ATTRIBUTE, Collections.singletonList(orgAttributeMap));
                if (!orgAttributeCreateBO.isSuccess()) {
                    Exceptions.throwBizException(ErrorCodeEnum.BO_SAVE_ERROR);
                }
            } else {
                // 存在时修改
                orgAttributeMap = Maps.newHashMap();
                orgAttributeMap.put("id", orgAttributeResultList.get(0).get("id"));
                orgAttributeMap.put("enabled", orgAttribute.getEnabled());
                log.info("------------------------更新组织属性数据，：{}------------------------", JSONObject.toJSONString(orgAttributeMap));
                SingleResponse<BO> orgAttributeCreateBO = BoServiceUtils.updateMainBo(ModelConst.T_ORGANIZATION_ATTRIBUTE, orgAttributeMap);
                if (!orgAttributeCreateBO.isSuccess()) {
                    Exceptions.throwBizException(ErrorCodeEnum.BO_UPDATE_ERROR);
                }
            }
        }
        return SingleResponse.of(true);
    }
}
